import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { Success } from '@/core/HttpException'
import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/system/value-set/listBySetCode'
import { ValueSet } from '@/common/typings/valueSet'
import { formatWhere } from '@/common/utils/sql'
export const setValueSelectSql = `SELECT id, set_code, set_name, code, name, parent_set_code, parent_set_name, created_at, status, updated_user_name, updated_at FROM system_value_set `
export async function valueSetListBySetCode({
  setCode = '',
  setName = '',
  code = '',
  name = '',
  parentSetCode = '',
  parentSetName = '',
  status = '1', // 默认只查询已启用的
  setCodes = [],
  onlySearchSetType = false,
  isPagination = false,
  isLike = false,
  pageSize = 1000,
  offset = 0,
}: any) {
  let where = `WHERE 1=1 ${
    setCode ? (isLike ? `AND set_code LIKE '%${setCode}%'` : ` AND set_code = '${setCode}'`) : ''
  } ${setName ? ` AND set_name LIKE '%${setName}%'` : ''} ${code ? ` AND code LIKE '%${code}%'` : ''} ${
    name ? ` AND name LIKE '%${name}%'` : ''
  } ${status ? ` AND status = '${status}'` : ''} ${
    parentSetCode ? ` AND parent_set_code LIKE '%${parentSetCode}%'` : ''
  } ${parentSetName ? ` AND parent_set_name LIKE '%${parentSetName}%'` : ''}`
  if (setCodes.length) {
    where = `WHERE 1=1 AND set_code IN (${setCodes.map((code: string) => `'${code}'`).join()})`
  }
  where = formatWhere(where)

  let total = 0
  let paginationStr = ''
  if (isPagination) {
    if (onlySearchSetType) {
      total = (
        await command(
          `SELECT COUNT(*) AS total FROM (SELECT DISTINCT set_code FROM system_value_set ${where}) t;`,
          true,
        )
      ).results[0].total
    } else {
      total = (await command(`SELECT COUNT(*) AS total FROM system_value_set ${where};`, true)).results[0].total
    }
    paginationStr = `LIMIT ${pageSize} OFFSET ${offset}`
  }
  let selectSql = `${setValueSelectSql} ${where} ${paginationStr};`
  if (onlySearchSetType) {
    selectSql = `
SELECT DISTINCT
    t3.set_code AS id,
    t3.set_code,
    t3.set_name,
    t4.summary,
    t3.parent_set_code,
    t3.parent_set_name
FROM
    (SELECT 
        t2.set_code, LEFT(GROUP_CONCAT(name), 100) AS summary
    FROM
        system_value_set t2
    WHERE
        t2.set_code IN (SELECT 
                t.set_code
            FROM
                system_value_set t ${where}
            GROUP BY set_code)
    GROUP BY set_code) t4
        LEFT JOIN
    system_value_set t3 ON t4.set_code = t3.set_code;`
  }
  const results = (await command(selectSql, true)).results as ValueSet.ValueSetItem[]
  return {
    total,
    results,
  }
}
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/valueSet`,
})
router.post('/listBySetCode', verifyToken, validator(schema, 'body'), async (ctx: Models.Ctx) => {
  const {
    setCode = '',
    setName = '',
    code = '',
    name = '',
    parentSetCode = '',
    parentSetName = '',
    status = '1',
    setCodes = [],
    onlySearchSetType = false,
    isPagination = false,
    isLike = false,
    pageSize = 1000,
    offset = 0,
  } = ctx.request.body as any
  const { results, total } = await valueSetListBySetCode({
    setCode,
    setName,
    code,
    name,
    parentSetCode,
    parentSetName,
    status,
    setCodes,
    onlySearchSetType,
    isPagination,
    isLike,
    pageSize,
    offset,
  })
  throw new Success({
    data: results,
    total,
  })
})
export default router
